import { getMenuListByType } from '@/api/classroom/videoReview'
import { listInfo } from '@/api/onlineClass/studentInfo'
import { getToken } from '@/framework/utils/auth'

const state = {
  onlineStudy: JSON.parse(sessionStorage.getItem('onlineStudy')) || [],
  studentList: JSON.parse(sessionStorage.getItem('studentList')) || [],
  studentInfo: JSON.parse(sessionStorage.getItem('studentInfo')) || {}
}

const mutations = {
  CHANGE_ONLINE_STUDY: (state, onlineStudy) => {
    state.onlineStudy = onlineStudy
    sessionStorage.setItem('onlineStudy', JSON.stringify(onlineStudy))
  },
  CHANGE_STUDENT_LIST: (state, studentList) => {
    state.studentList = studentList
    sessionStorage.setItem('studentList', JSON.stringify(studentList))
  },
  CHANGE_STUDENT_INFO: (state, studentInfo) => {
    state.studentInfo = studentInfo
    sessionStorage.setItem('studentInfo', JSON.stringify(studentInfo))
  }
}

const actions = {
  changeOnlineStudy({ commit }) {
    // commit('CHANGE_ONLINE_STUDY', data)
    getMenuListByType().then((res) => {
      const list = res.data.map((item) => {
        return {
          path: `/onlineClassroom/course?menuCode=${item.menuCode}&menuId=${item.id}`,
          name: 'classroomCourse',
          menuName: item.menuName,
          code: item.menuCode,
          menuId: item.id
        }
      })
      commit('CHANGE_ONLINE_STUDY', list)
    })
  },
  changeStudentList({ state, commit }) {
    const hasToken = getToken()
    if (hasToken) {
      listInfo().then((res) => {
        const studentList = res.data
        if (studentList.length) {
          commit('CHANGE_STUDENT_LIST', studentList)
          if (!state.studentInfo) {
            commit('CHANGE_STUDENT_INFO', studentList[0])
          } else {
            const obj = studentList.find((item) => item.id == state.studentInfo.id)
            if (!obj) {
              commit('CHANGE_STUDENT_INFO', studentList[0])
            } else if (obj.studentName != state.studentInfo.studentName) {
              commit('CHANGE_STUDENT_INFO', obj)
            }
          }
        } else {
          commit('CHANGE_STUDENT_LIST', [])
          commit('CHANGE_STUDENT_INFO', {})
        }
      })
    }
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

